# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: meta_ast.py 
@time: 2019/7/9 下午1:57
"""

'''
python源码的解析与分析
使用ast包
'''

import ast

# Example use
x = 42
# mode must be 'exec', 'eval' or 'single'
ex = ast.parse('2 + 3*4 + x', mode='eval')
print(ast.dump(ex))

ex = ast.parse('for i in range(10): print(i)', mode='exec')
print(ast.dump(ex))

'''
做一个代码分析
'''
class CodeAnalyzer(ast.NodeVisitor):
    def __init__(self):
        self.loaded = set()
        self.stored = set()
        self.deleted = set()

    def visit_Name(self, node):
        if isinstance(node.ctx, ast.Load):
            self.loaded.add(node.id)
        elif isinstance(node.ctx, ast.Store):
            self.stored.add(node.id)
        elif isinstance(node.ctx, ast.Del):
            self.deleted.add(node.id)

# Example usage
# Some python code
code = '''
for i in range(10):
    print(i)
del i
'''

# Parse into an AST
top = ast.parse(code, mode='exec')
c = CodeAnalyzer()
c.visit(top)
print('Loaded:', c.loaded)
print('Stored:', c.stored)
print('Deleted:', c.deleted)

# 通过AST包的compile()函数来编译并执行
exec (compile(top, '<stdin>', 'exec'))
